package skewreduce.lib;

import java.io.DataInput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class EndianConvertor implements DataInput {
    private ByteBuffer recBuf;
    private byte[] buf;
    private DataInput in;

    public EndianConvertor() {
        buf = new byte[8];
        recBuf = ByteBuffer.wrap(buf);
        recBuf.order(ByteOrder.LITTLE_ENDIAN);
    }

    public EndianConvertor(DataInput in) {
        this();
        set(in);
    }

    @Override
    public boolean readBoolean() throws IOException {
        return in.readBoolean();
    }

    @Override
    public byte readByte() throws IOException {
        return in.readByte();
    }

    @Override
    public char readChar() throws IOException {
        return in.readChar();
    }

    @Override
    public double readDouble() throws IOException {
        in.readFully(buf);
        recBuf.position(0).limit(8);
        return recBuf.getDouble();
    }

    @Override
    public float readFloat() throws IOException {
        in.readFully(buf,0,4);
        recBuf.position(0).limit(4);
        return recBuf.getFloat();
    }

    @Override
    public void readFully(byte[] b) throws IOException {
        in.readFully(b);
    }

    @Override
    public void readFully(byte[] b,int off,int len) throws IOException {
        in.readFully(b,off,len);
    }

    @Override
    public int readInt() throws IOException {
        in.readFully(buf,0,4);
        recBuf.position(0).limit(4);
        return recBuf.getInt();
    }

    @Override
    public String readLine() throws IOException {
        return in.readLine();
    }

    @Override
    public long readLong() throws IOException {
        in.readFully(buf);
        recBuf.position(0).limit(8);
        return recBuf.getLong();
    }

    @Override
    public short readShort() throws IOException {
        in.readFully(buf,0,2);
        recBuf.position(0).limit(2);
        return recBuf.getShort();
    }

    @Override
    public int readUnsignedByte() throws IOException {
        return in.readUnsignedByte();
    }

    @Override
    public int readUnsignedShort() throws IOException {
        return (int)(readShort() & 0x0ffff);
    }

    @Override
    public String readUTF() throws IOException {
        return in.readUTF();
    }

    @Override
    public int skipBytes(int n) throws IOException {
        return in.skipBytes(n);
    }

    public DataInput set(DataInput in) {
        this.in = in;
        return this;
    }
 }
